#!/usr/bin/python3.4
# -*- coding=utf-8 -*-
#ARP_1.py

import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)#清除报错
from scapy.all import *

#配置各种信息，以便调用
localmac = '00:0c:29:8d:5c:b6'
localip = '202.100.1.138'
destip = '202.100.1.139'
ifname = 'eno33554944'

result_raw = srp(Ether(src=localmac, dst='FF:FF:FF:FF:FF:FF')/ARP(op=1, hwsrc=localmac, hwdst='00:00:00:00:00:00', psrc=localip, pdst=destip), iface = ifname, verbose = False)

'''
sr() function is for sending packets and receiving answers. The function #returns a couple of packet and answers, and the unanswered packets. 
sr1() is a variant that only return one packet that answered the packet (or #the packet set) sent. The packets must be layer 3 packets (IP, ARP, etc.). 
srp() do the same for layer 2 packets (Ethernet, 802.3, etc.).
'''

#print(result_raw)
#(<Results: TCP:0 UDP:0 ICMP:0 Other:1>, <Unanswered: TCP:0 UDP:0 ICMP:0 Other:0>) 一个元组，[0]为收到的响应，[1]未收到响应的数据包
#print(type(result_raw[0]))
#<class 'scapy.plist.SndRcvList'>
result_list = result_raw[0].res #res: the list of packets
#print(result_list)
#[(<Ether  dst=FF:FF:FF:FF:FF:FF src=00:0c:29:8d:5c:b6 type=ARP |<ARP  op=who-has hwsrc=00:0c:29:8d:5c:b6 psrc=202.100.1.138 hwdst=00:00:00:00:00:00 pdst=202.100.1.139 |>>, <Ether  dst=00:0c:29:8d:5c:b6 src=00:0c:29:43:52:cf type=ARP |<ARP  hwtype=0x1 ptype=IPv4 hwlen=6 plen=4 op=is-at hwsrc=00:0c:29:43:52:cf psrc=202.100.1.139 hwdst=00:0c:29:8d:5c:b6 pdst=202.100.1.138 |<Padding load=‘\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00’ |>>>)]
#一个列表，每一个item为一个元组，元组内包括一次ARP请求与回应

#print(result_list[0][1][0].fields) 以太网头部字段
#{'dst': '00:0c:29:8d:5c:b6', 'type': 2054, 'src': '00:0c:29:43:52:cf'}
#print(result_list[0][1][1].fields) ARP头部字段
#{'pdst': '202.100.1.138', 'hwtype': 1, 'hwdst': '00:0c:29:8d:5c:b6', 'plen': 4, 'ptype': 2048, 'hwsrc': '00:0c:29:43:52:cf', 'op': 2, 'hwlen': 6, 'psrc': '202.100.1.139'}

print('IP地址: ' + result_list[0][1][1].fields['psrc'] + ' MAC地址: ' + result_list[0][1][1].fields['hwsrc'])

